<template>
    <div>
        <edu-dialog ref="advance" title="高级查询" width="800px" :autoHeight="true" id="advance-dialog">
            <el-row :gutter="20" class="scheme">
                <el-col :span="6" class="label">方案名称：</el-col>
                <el-col :span="10">
                    <el-select
                        style="width:100%"
                        v-model="selectedSchemeId"
                        @change="handleSchemeChange"
                        clearable
                    >
                        <el-option
                            v-for="(item,index) in schemes"
                            :key="'scheme-'+index"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-col>
                <el-col :span="8">
                    <el-button
                        type="primary"
                        @click="selectedSchemeId?updateScheme():addScheme()"
                    >保存方案</el-button>
                    <el-button type="primary" @click="deleteScheme">删除方案</el-button>
                </el-col>
            </el-row>
            <template v-for="(item,index) in conditions">
                <!-- 条件 -->
                <el-row :gutter="20" class="condition" :key="'c-'+index">
                    <el-col :span="6">
                        <div class="icon-btn">
                            <el-button
                                type="primary"
                                icon="el-icon-plus"
                                circle
                                size="mini"
                                @click="addCondition(index)"
                            ></el-button>
                            <el-button
                                v-if="conditions.length!=1"
                                type="primary"
                                icon="el-icon-minus"
                                circle
                                size="mini"
                                @click="removeCondtion(index)"
                            ></el-button>
                        </div>
                        <div class="cond">条件{{index+1}}：</div>
                    </el-col>
                    <el-col :span="10">
                        <el-input :style="{width:'100%;',display:(businessType === 'studentList'?'none':'inline') }"  v-model="item.name" maxlength="100"></el-input>
                    </el-col>
                    <el-col :span="8">
                        <el-button type="primary" @click="showNestedDialog(item,index)">嵌套条件</el-button>
                    </el-col>
                </el-row>
                <!-- 嵌套条件只读列表 开始-->
                <el-row :gutter="20" :key="'tip-'+index" v-if="item.isNested">
                    <el-col :span="6">&nbsp;</el-col>
                    <el-col :span="18">
                        <div class="hidden-list">
                            <div @click="handleNestedFold(item)">
                                <span class="text" v-if="item.showNested">隐藏嵌套条件</span>
                                <span class="text" v-else>展开嵌套条件</span>
                                <span class="arrow-down" v-if="item.showNested"></span>
                                <span class="arrow-up" v-else></span>
                            </div>
                            <div class="fields-list" v-show="item.showNested">
                                <template v-for="(field,index_) in item.conditionFields">
                                    <el-row :gutter="5" :key="index_">
                                        <el-col :span="3" style="text-align:right">
                                            <span>条件{{index_+1}}：</span>
                                        </el-col>
                                        <el-col :span="7">
                                            <el-select
                                                disabled
                                                style="width:100%"
                                                v-model="field.fieldId"
                                            >
                                                <el-option
                                                    v-for="(f,i) in options.fields"
                                                    :key="'f-'+i"
                                                    :label="f.label"
                                                    :value="f.value"
                                                ></el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="5">
                                            <el-select
                                                disabled
                                                style="width:100%"
                                                v-model="field.fieldCondition"
                                            >
                                                <el-option
                                                    v-for="(s,i) in field.symbols"
                                                    :key="'s-'+i"
                                                    :label="s.label"
                                                    :value="s.value"
                                                ></el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="9">
                                            <el-select
                                                disabled
                                                style="width:100%"
                                                v-model="field.fieldValue"
                                                v-if="field.fieldType=='select'&&!multiConnectionId.includes(field.fieldCondition)"
                                            >
                                                <el-option
                                                    v-for="(dic,i) in field.dic"
                                                    :key="'dic-'+i"
                                                    :label="dic.label"
                                                    :value="dic.value"
                                                ></el-option>
                                            </el-select>
                                            <el-select
                                                disabled
                                                style="width:100%"
                                                v-model="field.fieldValues"
                                                multiple
                                                collapse-tags
                                                v-else-if="field.fieldType=='select'&&multiConnectionId.includes(field.fieldCondition)"
                                            >
                                                <el-option
                                                    v-for="(dic,i) in field.dic"
                                                    :key="'dic-'+i"
                                                    :label="dic.label"
                                                    :value="dic.value"
                                                ></el-option>
                                            </el-select>
                                            <el-input
                                                disabled
                                                style="width:100%"
                                                v-model="field.fieldValue"
                                                v-else
                                            ></el-input>
                                        </el-col>
                                    </el-row>
                                    <!--只读条件关系-->
                                    <el-row
                                        :gutter="5"
                                        :key="'connection-type'+index_"
                                        v-if="index_!=item.conditionFields.length-1"
                                    >
                                        <el-col :span="3">&nbsp;</el-col>
                                        <el-col :span="7">
                                            <el-select
                                                style="width:70px"
                                                disabled
                                                v-model="field.fieldConnection"
                                            >
                                                <el-option
                                                    v-for="(t,i) in options.connectionType"
                                                    :key="'ctype-'+i"
                                                    :label="t.label"
                                                    :value="t.value"
                                                ></el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="14">&nbsp;</el-col>
                                    </el-row>
                                </template>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <!--嵌套条件只读列表 结束-->
                <!--字段行-->
                <el-row
                    :gutter="20"
                    :key="'f-'+index"
                    v-if="item.isNested==0&&item.conditionFields.length==1"
                >
                    <el-col :span="6">
                        <div class="label">字段名称：</div>
                    </el-col>
                    <el-col :span="10">
                        <el-row :gutter="10">
                            <el-col :span="12">
                                <category-select
                                    v-model="item.conditionFields[0].fieldId"
                                    :categorys="options.fieldCategorys"
                                    :options="options.fields"
                                    pop-width="300"
                                    @change="handleFieldChange(item.conditionFields[0])"
                                />
                            </el-col>
                            <el-col :span="12">
                                <el-select
                                    style="width:100%"
                                    filterable
                                    clearable
                                    v-model="item.conditionFields[0].fieldCondition"
                                    @change="connectionChange(item.conditionFields[0])"
                                >
                                    <el-option
                                        v-for="(symbol,i) in item.conditionFields[0].symbols"
                                        :key="i"
                                        :label="symbol.label"
                                        :value="symbol.value"
                                    ></el-option>
                                </el-select>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="8">
                        <el-select
                            v-if="item.conditionFields[0].fieldType=='select'&&!multiConnectionId.includes(item.conditionFields[0].fieldCondition)"
                            style="width:100%"
                            v-model="item.conditionFields[0].fieldValue"
                            filterable
                            clearable
                            :key="'field-single-select-'+index"
                            @change="handleValueChange(item,item.conditionFields[0])"
                        >
                            <el-option
                                v-for="item in item.conditionFields[0].dic"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <el-select
                            v-else-if="item.conditionFields[0].fieldType=='select'&&multiConnectionId.includes(item.conditionFields[0].fieldCondition)"
                            style="width:100%"
                            v-model="item.conditionFields[0].fieldValues"
                            multiple
                            collapse-tags
                            filterable
                            clearable
                            :key="'field-multi-select-'+index"
                            @change="handleValueChange(item,item.conditionFields[0])"
                        >
                            <el-option
                                v-for="item in item.conditionFields[0].dic"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>

                        <el-input
                            v-else-if="item.conditionFields[0].fieldType=='input'||item.conditionFields[0].fieldType=='textarea'"
                            style="width:100%"
                            v-model="item.conditionFields[0].fieldValue"
                        ></el-input>
                        <el-date-picker
                            v-else-if="item.conditionFields[0].fieldType=='year'"
                            v-model="item.conditionFields[0].fieldValue"
                            type="year"
                            style="width:100%"
                            value-format="yyyy"
                            placeholder="选择年份"
                        ></el-date-picker>
                        <el-date-picker
                            v-else-if="item.conditionFields[0].fieldType=='date'"
                            v-model="item.conditionFields[0].fieldValue"
                            format="yyyy-MM-dd"
                            style="width:100%"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期"
                        ></el-date-picker>
                    </el-col>
                </el-row>
                <!--条件连接关系,AND/OR-->
                <el-row
                    :gutter="20"
                    :key="'r-'+index"
                    class="relation"
                    v-if="index!=conditions.length-1"
                >
                    <el-col :span="6">&nbsp;</el-col>
                    <el-col :span="8">
                        <el-select
                            style="width:100px"
                            filterable
                            clearable
                            v-model="item.condiConnection"
                        >
                            <el-option
                                v-for="(t,i) in options.connectionType"
                                :key="i"
                                :label="t.label"
                                :value="t.value"
                            ></el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="10"></el-col>
                </el-row>
            </template>
            <template slot="buttons">
                <el-button @click="handleReturn">{{$t('message.return')}}</el-button>
                <el-button type="primary" @click="handleQuery">{{$t('message.query')}}</el-button>
            </template>
        </edu-dialog>
        <edu-dialog
            ref="nestedDialog"
            title="高级查询/嵌套条件"
            :autoHeight="true"
            id="advance-nested-dialog"
            @close="handleNestedDialog"
        >
            <template slot="buttons">
                <el-button @click="closeNestedDialog">{{$t('message.return')}}</el-button>
                <el-button type="primary" @click="saveNestedCondition">{{$t('message.save')}}</el-button>
            </template>
            <!--嵌套条件-->
            <template v-for="(item,index) in nestedFields">
                <el-row :gutter="20" :key="'nested-'+index" class="condition">
                    <el-col :span="6">
                        <div class="icon-btn">
                            <el-button
                                type="primary"
                                icon="el-icon-plus"
                                circle
                                size="mini"
                                @click="addNested(index)"
                            ></el-button>
                            <el-button
                                v-if="nestedFields.length!=1"
                                type="primary"
                                icon="el-icon-minus"
                                circle
                                size="mini"
                                @click="removeNested(index)"
                            ></el-button>
                        </div>
                        <div class="cond">条件{{index+1}}：</div>
                    </el-col>
                    <el-col :span="18">
                        <el-row :gutter="10">
                            <el-col :span="8">
                                <category-select
                                    v-model="item.fieldId"
                                    :categorys="options.fieldCategorys"
                                    :options="options.fields"
                                    pop-width="300"
                                    @change="handleFieldChange(item)"
                                />
                            </el-col>
                            <el-col :span="8">
                                <el-select
                                    style="width:100%"
                                    filterable
                                    clearable
                                    v-model="item.fieldCondition"
                                    @change="connectionChange(item)"
                                >
                                    <el-option
                                        v-for="(symbol,i) in item.symbols"
                                        :key="i"
                                        :label="symbol.label"
                                        :value="symbol.value"
                                    ></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="8">
                                <el-select
                                    v-if="item.fieldType=='select'&&!multiConnectionId.includes(item.fieldCondition)"
                                    style="width:100%"
                                    v-model="item.fieldValue"
                                    filterable
                                    clearable
                                    :key="'field-single-select-'+index"
                                >
                                    <el-option
                                        v-for="item_ in item.dic"
                                        :key="item_.value"
                                        :label="item_.label"
                                        :value="item_.value"
                                    />
                                </el-select>
                                <el-select
                                    v-else-if="item.fieldType=='select'&&multiConnectionId.includes(item.fieldCondition)"
                                    style="width:100%"
                                    v-model="item.fieldValues"
                                    multiple
                                    collapse-tags
                                    filterable
                                    clearable
                                    :key="'field-multi-select-'+index"
                                >
                                    <el-option
                                        v-for="item_ in item.dic"
                                        :key="item_.value"
                                        :label="item_.label"
                                        :value="item_.value"
                                    />
                                </el-select>
                                <el-input
                                    v-else-if="item.fieldType=='input'||item.fieldType=='textarea'"
                                    style="width:100%"
                                    v-model="item.fieldValue"
                                ></el-input>
                                <el-date-picker
                                    v-else-if="item.fieldType=='year'"
                                    v-model="item.fieldValue"
                                    type="year"
                                    style="width:100%"
                                    value-format="yyyy"
                                    placeholder="选择年份"
                                ></el-date-picker>
                                <el-date-picker
                                    v-else-if="item.fieldType=='date'"
                                    v-model="item.fieldValue"
                                    format="yyyy-MM-dd"
                                    style="width:100%"
                                    value-format="yyyy-MM-dd"
                                    placeholder="选择日期"
                                ></el-date-picker>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
                <!--条件连接关系,AND/OR-->
                <el-row
                    :gutter="20"
                    :key="'nested-r-'+index"
                    class="relation"
                    v-if="index!=nestedFields.length-1"
                >
                    <el-col :span="6">&nbsp;</el-col>
                    <el-col :span="8">
                        <el-select
                            style="width:100px"
                            filterable
                            clearable
                            v-model="item.fieldConnection"
                        >
                            <el-option
                                v-for="(t,i) in options.connectionType"
                                :key="i"
                                :label="t.label"
                                :value="t.value"
                            ></el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="10"></el-col>
                </el-row>
            </template>
        </edu-dialog>
    </div>
</template>
<script>
import fetch from "common/src/utils/fetch";
import { queryDic } from "common/src/api/dictionary";
export default {
    name: "AdvanceSearch",
    props: {
        //业务类型
        businessType: {
            type: String,
            required: true
        },
        //字段列表接口，各业务类型自己提供
        fieldsApi: {
            type: String,
            required: true
        },
        //查询接口，各业务类型自己提供，返回数据列表
        searchApi: {
            type: String,
            required: true
        },
        //字段列表接口请求方式
        fieldsApiMethod: {
            type: String,
            default: "get"
        },
        //字段列表接口请求参数
        fieldsApiParams: {
            type: Object,
            default: null
        },
        //查询接口请求方式
        searchApiMethod: {
            type: String,
            default: "get"
        },
        //查询接口请求参数
        searchApiParams: {
            type: Object,
            default: null
        },
        // 特殊情况，下拉列表数据来源为接口
        searchParm: {
            type: Object,
            default: {}
        }
    },
    data() {
        return {
            preUrl: "/api/studentservice/advancedQuery/",
            schemes: null, //方案列表
            selectedSchemeId: null, //当前选中方案id
            selectedSchemeName: null, //当前选中方案name
            fields: null, //字段列表
            conditions: null, //条件列表
            nestedIndex: null, //嵌套条件索引,
            nestedFields: null, //嵌套条件列表
            options: {
                fields: [],
                connectionType: null, //条件之间的关系类型
                fieldCategorys: [] //字段分类
            },
            nestedDialogRealClose: false,
            //条件数据结构
            condition: {
                id: null,
                name: null, //条件名
                schemeId: null, //方案
                isNested: 0, //是否嵌套
                condiConnection: "and", //条件连接逻辑
                conditionIndex: null, //条件顺序
                conditionFields: null, //字段条件集合,
                showNested: false //是否显示嵌套
            },
            //字段条件数据结构
            conditionField: {
                id: null,
                conditionId: null, //条件id
                fieldId: null, //字段id
                fieldCondition: null, //字段条件
                fieldValue: null, //字段值
                fieldValues: [], //字段值多选
                fieldIndex: null, //字段顺序
                fieldConnection: "and", //关联逻辑
                symbols: [], //
                fieldType: null, //字段类型,如select,input
                dic: []
            },
            conditionsCopy: null,
            multiConnectionId: [2, 4] //等于多个值，不等于多个值
        };
    },
    created() {
        this.options.connectionType = [
            {
                label: "并且",
                value: "and"
            },
            {
                label: "或者",
                value: "or"
            }
        ];
        this.options.fieldCategorys = [
            {
                label: "基础信息",
                value: [
                    "student_basic_information_t",
                    "student_contact_information_t"
                ]
            },
            {
                label: "学籍信息",
                value: [
                    "student_status_information_t",
                    "student_admission_information_t"
                ]
            },
            {
                label: "教育背景",
                value: ["student_educational_backgroud_t"]
            },
            {
                label: "工作经历",
                value: ["student_work_experience_t"]
            },
            {
                label: "联合培养",
                value: ["student_joint_training_t"]
            },
            {
                label: "证件信息",
                value: ["student_paperwork_t"]
            },
            {
                label: "联系人",
                value: ["student_family_members_t"]
            },
            {
                label: "宿舍",
                value: ["student_dormitory_t"]
            },
            {
                label: "其他",
                value: ["student_passport_t", "student_other_infomation_t"]
            },
            {
                label: "学籍变更日志",
                value: ["stu_field_log_t"]
            }
        ];
    },
    mounted() {
        this.getSchemes();
        this.getFields();
        this.open();
    },
    methods: {
        open() {
            if (this.schemes == null) {
                this.getSchemes();
            }
            if (this.fields == null) {
                this.getFields();
            }
            this.selectedSchemeId = null;
            this.$refs.advance.open();
            this.conditions = [this.createCondition()];
        },
        getFields() {
            if (this.fieldsApi) {
                return fetch({
                    url: this.fieldsApi,
                    method: this.fieldsApiMethod,
                    data: this.fieldsApiParams
                }).then(res => {
                    if (res.code == 200) {
                        this.fields = res.data;
                        this.options.fields = res.data.map(f => {
                            return {
                                label: f.name,
                                value: f.id,
                                categoryId: f.tableStr
                            };
                        });
                    }
                });
            }
        },
        // 获取匹配符号,如大于、等于、小于
        getSymbols(field, item) {
            fetch({
                url: this.preUrl + "filterFieldCondi",
                method: "post",
                data: {
                    type: field.type,
                    dataType: field.dataType
                }
            }).then(res => {
                if (res.code == 200 && res.data) {
                    item.symbols = res.data.map(f => {
                        return {
                            label: f.nameCh,
                            value: f.id
                        };
                    });
                }
            });
        },
        // 获取方案列表
        getSchemes() {
            fetch({
                url:
                    this.preUrl +
                    "queryAdvancedScheme?businessType=" +
                    this.businessType
            }).then(res => {
                if (res.code == 200) {
                    this.schemes = res.data.map(scheme => {
                        return {
                            label: scheme.name,
                            value: scheme.id
                        };
                    });
                }
            });
        },
        search() {
            if (this.searchApi) {
                if(this.businessType === 'studentList' && this.conditions && this.conditions.length > 0) {
                    this.conditions.forEach((con,index) => {
                        con.name = '条件' + index
                    })
                }
                let params = this.searchApiParams
                    ? this.searchApiParams
                    : {
                          id: this.selectedSchemeId,
                          name: this.selectedSchemeName,
                          businessType: this.businessType,
                          conditions: _.cloneDeep(this.conditions)
                      };
                if (!this.searchApiParams) {
                    params.conditions.forEach((condition_, index) => {
                        //去掉条件尾项关系
                        if (index == params.conditions.length - 1) {
                            condition_.condiConnection = null;
                        }
                        condition_.conditionFields.forEach((field_, index_) => {
                            //去掉字段尾项关系
                            if (
                                index_ ==
                                condition_.conditionFields.length - 1
                            ) {
                                field_.fieldConnection = null;
                            }
                            if (
                                field_.fieldType == "select" &&
                                this.multiConnectionId.includes(
                                    field_.fieldCondition
                                )
                            ) {
                                field_.fieldValue = field_.fieldValues.join(
                                    ","
                                );
                            }
                        });
                    });
                }
                return fetch({
                    url: this.searchApi,
                    method: this.searchApiMethod,
                    data: params
                }).then(res => {
                    if (res.code == 200) {
                        this.$emit("advanceQuery", res.data);
                        this.$refs.advance.close();
                    }
                });
            }
        },
        //获取默认条件改变状态
        getConditionChanged() {
            if (
                this.conditions.length != 1 ||
                this.conditions[0].condiConnection !=
                    this.condition.condiConnection ||
                this.conditions[0].isNested != 0
            ) {
                return true;
            }
            if (
                this.conditions[0].name != null &&
                this.conditions[0].name != ""
            ) {
                return true;
            }
            if (this.conditions[0].conditionFields[0].fieldType != null) {
                return true;
            }
            return false;
        },
        //获取某方案条件改变状态
        getSchemeConditionChanged() {
            if (this.conditions.length != this.conditionsCopy.length) {
                return true;
            }
            for (let i = 0; i < this.conditions.length; i++) {
                let new_ = this.conditions[i];
                let old_ = this.conditionsCopy[i];
                if (
                    new_.condiConnection != old_.condiConnection ||
                    new_.id != old_.id ||
                    new_.isNested != old_.isNested ||
                    new_.name != old_.name ||
                    new_.conditionFields.length != old_.conditionFields.length
                ) {
                    return true;
                }
                for (let j = 0; j < new_.conditionFields.length; j++) {
                    let newField = new_.conditionFields[j];
                    let oldField = old_.conditionFields[j];
                    if (
                        newField.conditionId != oldField.conditionId ||
                        newField.fieldCondition != oldField.fieldCondition ||
                        newField.fieldConnection != oldField.fieldConnection ||
                        newField.fieldId != oldField.fieldId ||
                        newField.fieldType != oldField.fieldType ||
                        newField.fieldValue != oldField.fieldValue ||
                        newField.id != oldField.id ||
                        newField.fieldValues.join(",") !=
                            oldField.fieldValues.join(",")
                    ) {
                        return true;
                    }
                }
            }
            return false;
        },
        handleReturn() {
            let changed = false;
            if (this.selectedSchemeId) {
                changed = this.getSchemeConditionChanged();
            } else {
                changed = this.getConditionChanged();
            }
            if (changed) {
                this.$confirm(
                    "返回后您的当前操作将不会保存，请确认操作",
                    this.$t("message.prompt"),
                    {
                        confirmButtonText: this.$t("message.confirm"),
                        cancelButtonText: this.$t("message.cancel"),
                        type: "warning"
                    }
                ).then(() => {
                    this.$refs.advance.close();
                });
            } else {
                this.$refs.advance.close();
            }
        },
        handleQuery() {
            if (this.selectedSchemeId) {
                if (this.getSchemeConditionChanged()) {
                    this.$message({
                        type: "warning",
                        message: "当前方案已改变，请先保存当前方案"
                    });
                } else {
                    this.search();
                }
            } else {
                if (this.getConditionChanged()) {
                    this.$message({
                        type: "warning",
                        message: "请先保存当前方案"
                    });
                } else {
                    this.$message({
                        type: "warning",
                        message: "请选择要查询的方案"
                    });
                }
            }
        },
        handleNestedDialog() {
            if (!this.nestedDialogRealClose) {
                this.$refs.nestedDialog.open();
                this.closeNestedDialog();
            }
        },
        //处理嵌套列表折叠
        handleNestedFold(condition, event) {
            condition.showNested = !condition.showNested;
        },
        //方案改变时，获取方案信息
        handleSchemeChange() {
            if (this.selectedSchemeId) {
                fetch({
                    url:
                        this.preUrl +
                        "queryAdvancedCondi?schemeId=" +
                        this.selectedSchemeId
                }).then(res => {
                    if (res.code == 200 && res.data) {
                        this.conditions = res.data.map(c => {
                            c.conditionFields.forEach(field => {
                                field.fieldType = null;
                                field.symbols = null;
                                field.dic = [];
                                field.fieldValues = [];
                            });
                            c.showNested = false;
                            return c;
                        });
                        this.conditions.forEach((con, index) => {
                            if (index == this.conditions.length - 1) {
                                con.condiConnection = this.condition.condiConnection;
                            }
                            con.conditionFields.forEach((field, index_) => {
                                //若是多选select，转换值到集合
                                if (
                                    this.fields.find(v => v.id == field.fieldId)
                                        .type == "select" &&
                                    this.multiConnectionId.includes(
                                        field.fieldCondition
                                    )
                                ) {
                                    field.fieldValues = field.fieldValue.split(
                                        ","
                                    );
                                }
                                if (index_ == con.conditionFields.length - 1) {
                                    field.fieldConnection = this.condition.condiConnection;
                                }
                                this.handleFieldChange(field, false);
                            });
                        });
                        this.conditionsCopy = _.cloneDeep(this.conditions);
                    }
                });
                let scheme = this.schemes.find(
                    s => s.value == this.selectedSchemeId
                );
                this.selectedSchemeName = scheme.label;
            } else {
                this.selectedSchemeName = null;
                this.conditions = [this.createCondition()];
            }
        },
        //处理字段改变
        handleFieldChange(item, reset = true) {
            let _this = this
            item.dic = [];
            if (reset) {
                item.fieldValue = null;
                item.fieldCondition = null;
                item.fieldValues = [];
            }
            if (item.fieldId) {
                let field = this.fields.find(v => v.id == item.fieldId);
                item.fieldType = field.type;
                this.getSymbols(field, item);
                if (
                    field.type === "select" &&
                    field.value != null &&
                    field.value != ""
                ) {
                    let data = {
                        lang: this.$store.getters.language || "cn",
                        type: "allChild",
                        keys: [field.value]
                    };
                    //当前字段为专业
                    if (
                        field &&
                        field.type === "select" &&
                        field.value === "G_ZY"
                    ) {
                        this.setFacultyCode(data);
                    }
                    queryDic(data).then(res => {
                        if (res.code == 200) {
                            for (let key in res.data[field.value]) {
                                item.dic.push({
                                    label: res.data[field.value][key],
                                    value: key.toString()
                                });
                            }
                        }
                    });
                } else if(_this.searchParm && _this.searchParm.api && _this.searchParm.label && _this.searchParm.value) {
                    return fetch({
                    url: _this.searchParm.api,
                    method: _this.searchParm.method,
                    data: _this.searchParm.parm
                    }).then(res => {
                        if (res.code == 200 && res.data) {
                                let searchLabel = _this.searchParm.label
                                let searchValue = _this.searchParm.value
                                res.data.forEach(val=> {
                                item.dic.push(
                                    {
                                        label: val[searchLabel],
                                        value: val[searchValue]
                                    }
                                )
                            })
                        }
                    });
                }
            } else {
                item.fieldType = null;
                item.symbols = [];
                item.dic = [];
                item.fieldCondition = null;
                item.fieldValues = [];
                item.fieldValue = null;
            }
        },
        handleValueChange(condition, field) {
            //条件为嵌套，直接返回
            if (condition.isNested) {
                return;
            }
            let facultyField = this.fields.find(
                f => f.id == field.fieldId && f.columnStr === "FACULTY_"
            );
            //当前改变项不是学院，直接返回
            if (facultyField == null) {
                return;
            }
            let professions = [];
            this.conditions
                .filter(c => !c.isNested)
                .forEach(c => {
                    c.conditionFields.forEach(f => {
                        if (
                            this.fields.find(
                                f_ => f_.id == f.fieldId && f_.value === "G_ZY"
                            )
                        ) {
                            professions.push(f);
                        }
                    });
                });
            //当前条件中无专业，直接返回
            if (professions.length === 0) {
                return;
            }
            //遍历获取所有学院code
            let facultyCode = [];
            this.conditions
                .filter(
                    c =>
                        !c.isNested &&
                        c.condiConnection === this.condition.condiConnection
                )
                .forEach(c => {
                    c.conditionFields.forEach(f => {
                        if (f.fieldId == facultyField.id && f.fieldValue) {
                            facultyCode.push(f.fieldValue);
                        } else if (
                            f.fieldId == facultyField.id &&
                            f.fieldValues.length > 0
                        ) {
                            facultyCode = facultyCode.concat(f.fieldValues);
                        }
                    });
                });
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["G_ZY"],
                filter: {
                    facultys: facultyCode,
                    prefix: facultyCode,
                    specilaCode: "XY2ZY"
                }
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    professions.forEach(p => {
                        p.dic = [];
                        p.fieldValue = null;
                        p.fieldValues = [];
                        for (let key in res.data["G_ZY"]) {
                            p.dic.push({
                                label: res.data["G_ZY"][key],
                                value: key.toString()
                            });
                        }
                    });
                }
            });
        },
        setFacultyCode(data) {
            //若无学院字段，查询所有专业
            let facultyField = this.fields.find(
                c => c.columnStr === "FACULTY_"
            );
            if (facultyField == null) {
                data.filter = {
                    prefix: null,
                    specilaCode: "XY2ZY",
                    facultys: null
                };
                return;
            }
            //关联AND关系的条件，排除嵌套条件
            let facultyCode = [];
            this.conditions
                .filter(
                    c =>
                        !c.isNested &&
                        c.condiConnection === this.condition.condiConnection
                )
                .forEach(c => {
                    //添加所有学院code，包括单选和多选
                    c.conditionFields.forEach(f => {
                        if (f.fieldId == facultyField.id && f.fieldValue) {
                            facultyCode.push(f.fieldValue);
                        } else if (
                            f.fieldId == facultyField.id &&
                            f.fieldValues.length > 0
                        ) {
                            facultyCode = facultyCode.concat(f.fieldValues);
                        }
                    });
                });
            if (facultyCode.length > 0) {
                data.filter = {
                    prefix: facultyCode,
                    specilaCode: "XY2ZY",
                    facultys: facultyCode
                };
            } else {
                data.filter = {
                    prefix: null,
                    specilaCode: "XY2ZY",
                    facultys: null
                };
            }
        },
        //创建条件行
        createCondition() {
            let condition = _.cloneDeep(this.condition);
            if (this.selectedSchemeId) {
                condition.schemeId = this.selectedSchemeId;
            }
            condition.conditionFields = [];
            condition.conditionFields.push(_.cloneDeep(this.conditionField));
            return condition;
        },
        //添加条件
        addCondition(index) {
            if (index == this.conditions.length - 1) {
                this.conditions.push(this.createCondition());
            } else {
                this.conditions = this.conditions
                    .slice(0, index + 1)
                    .concat(
                        this.createCondition(),
                        this.conditions.slice(index + 1)
                    );
            }
        },
        //移除条件
        removeCondtion(index) {
            this.conditions = this.conditions.filter(
                (item, index_) => index != index_
            );
        },
        //添加嵌套行
        addNested(index) {
            let fieldRow = _.cloneDeep(this.conditionField);
            if (this.selectedSchemeId) {
                fieldRow.conditionId = this.conditions[this.nestedIndex].id;
            }
            if (index == this.nestedFields.length - 1) {
                this.nestedFields.push(fieldRow);
            } else {
                this.nestedFields = this.nestedFields
                    .slice(0, index + 1)
                    .concat(fieldRow, this.nestedFields.slice(index + 1));
            }
        },
        //移除嵌套行
        removeNested(index) {
            this.nestedFields = this.nestedFields.filter(
                (item, index_) => index != index_
            );
        },
        validScheme() {
            let msg = null;
            let index = 0;
            for (let condition of this.conditions) {
                if (
                    condition.name == null ||
                    condition.name == "" ||
                    condition.name.replace(/ /g, "").length == 0
                ) {
                    
                    if(this.businessType === 'studentList') { 
                        condition.name = "条件" + (index + 1)
                    } else {
                        msg = "条件" + (index + 1) + "名称必须填写";
                        break;
                    }
                    
                }
                if (
                    index != this.conditions.length - 1 &&
                    (condition.condiConnection == null ||
                        condition.condiConnection == "")
                ) {
                    msg =
                        "条件" +
                        (index + 1) +
                        "与条件" +
                        (index + 2) +
                        "关系必须选择";
                    break;
                }
                if (condition.isNested == 0) {
                    msg = this.validFieldsRequire(
                        condition.conditionFields,
                        index
                    );
                    if (msg) break;
                }
                index++;
            }
            if (msg) {
                this.$message({
                    type: "warning",
                    message: msg
                });
                return false;
            } else {
                //验证字段数据
                for (let i = 0; i < this.conditions.length; i++) {
                    let result = this.validFieldsVal(
                        this.conditions[i].conditionFields
                    );
                    if (!result) return false;
                }
            }
            return true;
        },
        //验证Field必填
        validFieldsRequire(fields, index = 0) {
            let msg = null;
            let fieldIndex = 0;
            for (let field of fields) {
                if (field.fieldId == null || field.fieldId == "") {
                    msg = "条件" + (index + 1) + "必须选择字段";
                    break;
                }
                if (
                    field.fieldCondition == null ||
                    field.fieldCondition == ""
                ) {
                    msg = "条件" + (index + 1) + "必须选择字段条件";
                    break;
                }
                if (field.fieldType != "select") {
                    if (field.fieldValue == null || field.fieldValue == "") {
                        msg = "条件" + (index + 1) + "必须填写字段值";
                        break;
                    }
                } else if (
                    this.multiConnectionId.includes(field.fieldCondition) &&
                    field.fieldValues.length == 0
                ) {
                    msg = "条件" + (index + 1) + "必须选择字段值";
                    break;
                } else if (
                    !this.multiConnectionId.includes(field.fieldCondition) &&
                    (field.fieldValue == null || field.fieldValue == "")
                ) {
                    msg = "条件" + (index + 1) + "必须选择字段值";
                    break;
                }
                if (
                    fieldIndex != fields.length - 1 &&
                    (field.fieldConnection == null ||
                        field.fieldConnection == "")
                ) {
                    msg =
                        "条件" +
                        (index + 1) +
                        "与条件" +
                        (index + 2) +
                        "关系必须选择";
                    break;
                }
                index++;
                fieldIndex++;
            }
            return msg;
        },
        //验证Field值
        validFieldsVal(fields) {
            for (let i = 0; i < fields.length; i++) {
                //排除select,date,year字段类型
                if (fields[i].fieldType != "input") {
                    continue;
                }
                let field = this.fields.find(c => c.id == fields[i].fieldId);
                let type = field ? field.dataType : null;
                let val = fields[i].fieldValue;
                if (type == "int" || type == "long") {
                    let msg;
                    if (isNaN(Number(val))) {
                        msg = "字段 '" + field.name + "' 输入必须是数字";
                    } else if (val % 1 !== 0) {
                        msg = "字段 '" + field.name + "' 输入必须是整数";
                    }
                    if (msg) {
                        this.$message({
                            type: "warning",
                            message: msg
                        });
                        return false;
                    }
                } else if (type == "float" && isNaN(Number(val))) {
                    this.$message({
                        type: "warning",
                        message: "字段 '" + field.name + "' 输入必须是数字"
                    });
                    return false;
                }
            }
            return true;
        },
        //添加方案
        addScheme() {
            if (!this.validScheme()) {
                return;
            }
            if (this.checkSameConditionName()) {
                return;
            }
            this.$prompt("请输入方案名称", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                inputValidator: value => {
                    if (value == null || value == "") {
                        return false;
                    }
                    if (value.indexOf(" ") != -1) {
                        return false;
                    }
                    if (value.length > 15) {
                        return false;
                    }
                    return true;
                },
                inputErrorMessage:
                    "必须填写，且不能包含空格，长度不超过15个字符"
            })
                .then(result => {
                    this.AddOrUpdateScheme(result.value);
                })
                .catch(() => {});
        },
        checkSameConditionName() {
            let sameName = false;
            let names = [];
            this.conditions.forEach(condition => {
                if (names.includes(condition.name)) {
                    sameName = true;
                }
                names.push(condition.name);
            });
            if (sameName) {
                this.$message({
                    type: "warning",
                    message: "条件名不能相同"
                });
            }
            return sameName;
        },
        //添加或更新方案
        AddOrUpdateScheme(schemeName, id) {
            let param = {
                businessType: this.businessType,
                name: schemeName,
                conditions: _.cloneDeep(this.conditions)
            };
            if (id) {
                param.id = id;
            }
            param.conditions.forEach((condition, index) => {
                condition.conditionIndex = index;
                //去掉条件尾项关系
                if (index == param.conditions.length - 1) {
                    condition.condiConnection = null;
                }
                condition.conditionFields.forEach((field, index_) => {
                    field.fieldIndex = index_;
                    //去掉字段尾项关系
                    if (index_ == condition.conditionFields.length - 1) {
                        field.fieldConnection = null;
                    }
                    if (
                        field.fieldType == "select" &&
                        this.multiConnectionId.includes(field.fieldCondition)
                    ) {
                        field.fieldValue = field.fieldValues.join(",");
                    }
                    //接口不关注的额外属性
                    field.fieldType = null;
                    field.symbols = null;
                    field.dic = null;
                    field.fieldValues = null;
                });
            });
            fetch({
                url: this.preUrl + "addAdvancedQuery",
                method: "post",
                data: param
            }).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: "success",
                        message: id ? "更新成功" : "添加成功"
                    });
                    if (!id && res.data && res.data.length == 1) {
                        this.schemes.push({
                            label: schemeName,
                            value: res.data[0]
                        });
                        this.conditions = [this.createCondition()];
                    }
                    if (id) {
                        this.handleSchemeChange();
                    }
                }
            });
        },
        //更新方案
        updateScheme() {
            if (!this.validScheme()) {
                return;
            }
            if (this.checkSameConditionName()) {
                return;
            }
            this.AddOrUpdateScheme(
                this.selectedSchemeName,
                this.selectedSchemeId
            );
        },
        //删除当前选中方案
        deleteScheme() {
            if (!this.selectedSchemeId) {
                this.$message({
                    type: "warning",
                    message: "请选中需要删除的方案"
                });
                return;
            }
            this.$confirm(
                "是否确认删除该高级查询方案？",
                this.$t("message.prompt"),
                {
                    confirmButtonText: this.$t("message.yes"),
                    cancelButtonText: this.$t("message.no"),
                    type: "warning"
                }
            ).then(() => {
                fetch({
                    url:
                        this.preUrl +
                        "deleteAdvancedScheme?schemeId=" +
                        this.selectedSchemeId,
                    method: "get"
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: this.$t("message.deleteSuccess")
                        });
                        this.schemes = this.schemes.filter(
                            scheme => scheme.value != this.selectedSchemeId
                        );
                        this.selectedSchemeId = null;
                        this.conditions = [this.createCondition()];
                    }
                });
            });
        },
        showNestedDialog(item, index) {
            this.nestedIndex = index;
            this.nestedFields = _.cloneDeep(item.conditionFields);
            this.$refs.nestedDialog.open();
            this.nestedDialogRealClose = false;
        },
        closeNestedDialog() {
            let fn = () => {
                this.nestedFields = null;
                this.nestedIndex = null;
                this.nestedDialogRealClose = true;
                this.$refs.nestedDialog.close();
            };
            if (this.nestedConditionIsChanged()) {
                this.$confirm(
                    "嵌套条件已改变, 返回将放弃改变?",
                    this.$t("message.prompt"),
                    {
                        confirmButtonText: this.$t("message.confirm"),
                        cancelButtonText: this.$t("message.cancel"),
                        type: "warning"
                    }
                ).then(() => {
                    fn();
                });
            } else {
                fn();
            }
        },
        //嵌套条件是否改变
        nestedConditionIsChanged() {
            //对比长度
            if (
                this.conditions[this.nestedIndex].conditionFields.length !=
                this.nestedFields.length
            ) {
                return true;
            }
            let changed = false;
            //对比实际值
            let compareFn = (attr, index, item) => {
                let oldVal =
                    this.conditions[this.nestedIndex].conditionFields[index][
                        attr
                    ] == null
                        ? ""
                        : this.conditions[this.nestedIndex].conditionFields[
                              index
                          ][attr];
                let nowVal = item[attr] == null ? "" : item[attr];
                return oldVal == nowVal ? false : true;
            };
            let index = 0;
            for (let item of this.nestedFields) {
                changed = compareFn("id", index, item);
                if (changed) break;
                changed = compareFn("conditionId", index, item);
                if (changed) break;
                changed = compareFn("fieldId", index, item);
                if (changed) break;
                changed = compareFn("fieldCondition", index, item);
                if (changed) break;
                changed = compareFn("fieldConnection", index, item);
                if (changed) break;
                changed = compareFn("fieldType", index, item);
                if (changed) break;
                changed = compareFn("fieldValue", index, item);
                if (changed) break;
                index++;
            }
            return changed;
        },
        validNestedCondition() {
            let msg = this.validFieldsRequire(this.nestedFields);
            if (msg) {
                this.$message({
                    type: "warning",
                    message: msg
                });
                return false;
            }
            return true;
        },
        //保存嵌套条件
        saveNestedCondition() {
            if (!this.validNestedCondition()) {
                return;
            }
            if (!this.validFieldsVal(this.nestedFields)) {
                return;
            }
            this.conditions[
                this.nestedIndex
            ].conditionFields = this.nestedFields;
            this.conditions[this.nestedIndex].isNested = 1;
            this.nestedFields = null;
            this.nestedIndex = null;
            this.nestedDialogRealClose = true;
            this.$refs.nestedDialog.close();
        },
        //检查是否为空条件
        checkEmptyCondition() {
            for (let condition of this.conditions) {
                if (condition.name != null && condition.name != "") {
                    return false;
                }
                if (
                    condition.condiConnection != null &&
                    condition.condiConnection != ""
                ) {
                    return false;
                }
                if (condition.conditionFields) {
                    for (let field of condition.conditionFields) {
                        if (field.fieldId != null && field.fieldId != "") {
                            return false;
                        }
                        if (
                            field.fieldCondition != null &&
                            field.fieldCondition != ""
                        ) {
                            return false;
                        }
                        if (
                            field.fieldConnection != null &&
                            field.fieldConnection != ""
                        ) {
                            return false;
                        }
                        if (
                            field.fieldValue != null &&
                            field.fieldValue != ""
                        ) {
                            return false;
                        }
                    }
                }
            }
            return true;
        },
        connectionChange(field) {
            if (field.fieldType == "select") {
                field.fieldValue = null;
                field.fieldValues = [];
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.label {
    line-height: 30px;
    text-align: right;
}
.scheme {
    padding-bottom: 18px;
    border-bottom: 1px solid #e5e5e5;
}
.condition {
    margin: 18px 0;
    .icon-btn {
        float: left;
        margin-top: 5px;
        margin-left: 25px;
    }
    .cond {
        float: right;
        margin-top: 5px;
    }
}
.relation {
    margin: 18px 0;
}
#advance-dialog,
#advance-nested-dialog {
    ::v-deep .edu-dialog_body {
        padding: 20px;
    }
    ::v-deep .el-button--mini.is-circle {
        padding: 1px;
    }
}
.hidden-list {
    .text {
        color: #3a7fe8;
        cursor: pointer;
    }
    .arrow-down {
        position: relative;
        top: 3px;
        border: 5px solid #3a7fe8;
        border-left-color: transparent;
        border-right-color: transparent;
        border-bottom-color: transparent;
        display: inline-block;
        margin-left: 5px;
        cursor: pointer;
    }
    .arrow-up {
        position: relative;
        top: -3px;
        border: 5px solid #3a7fe8;
        border-left-color: transparent;
        border-right-color: transparent;
        border-top-color: transparent;
        display: inline-block;
        margin-left: 5px;
        cursor: pointer;
    }
    .fields-list {
        border: 1px dashed #d9d9d9;
        padding: 5px;
        margin-top: 5px;
        span {
            line-height: 30px;
        }
        & > div + div {
            margin-top: 5px;
        }
    }
}
</style>>